<template>
  <div class="category">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col :span="24">
          <el-button type="primary" @click="addCate">
            添加分类
          </el-button>
        </el-col>
      </el-row>
      <tree-table
        :data="cateList"
        :columns="column"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
      >
        <template v-slot:isOk="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color:lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color:red"> </i>
        </template>
        <template v-slot:order="scoper">
          <el-tag v-if="scoper.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scoper.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <template v-slot:operation="opt">
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="getRowCate(opt.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="showDeleteCate(opt.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 添加分类 -->
      <el-dialog
        title="添加分类"
        :visible.sync="showAddDialog"
        width="30%"
        @close="closeAddDiglog"
      >
        <el-form
          :model="addCateForm"
          ref="addCateRef"
          label-width="100px"
          :rules="addCateRules"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <!--    options指定数据源 -->
            <el-cascader
              v-model="selectoption"
              :options="parentCateList"
              :props="parentCate"
              @change="handleAddChange"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showAddDialog = false">取 消</el-button>
          <el-button type="primary" @click="commitAdd">确 定</el-button>
        </span>
      </el-dialog>
      <!--  编辑分类 -->
      <el-dialog
        title="编辑分类"
        :visible.sync="showEditDialog"
        width="30%"
        @close="closeEdit"
      >
        <el-form
          :model="rowCateForm"
          ref="editCateRef"
          label-width="100px"
          :rules="editCateRules"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="rowCateForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showEditDialog = false">取 消</el-button>
          <el-button type="primary" @click="commitEdit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 删除 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="queryInfo.pagenum"
        :page-sizes="[3, 4, 5, 6, 7]"
        :page-size="queryInfo.pagesize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "",
  components: {},
  data() {
    return {
      cateList: [],
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      total: 0,
      column: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          //将当前列定义为模板列
          type: "template",
          template: "isOk",
        },
        {
          label: "排序",
          //将当前列定义为模板列
          type: "template",
          template: "order",
        },
        {
          label: "操作",
          //将当前列定义为模板列
          type: "template",
          template: "operation",
        },
      ],
      showAddDialog: false,
      //添加分类的表单
      addCateForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0, //默认一级分类
      },
      addCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      editCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      parentCateList: [],
      parentCate: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: "true",
      },
      selectoption: [],

      showEditDialog: false,
      rowCateForm: {},
    };
  },
  methods: {
    async getCate() {
      const { data: res } = await this.$request({
        url: "categories",
        params: this.queryInfo,
      });
      //console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.cateList = res.data.result;
      //console.log(this.cateList);
      this.total = res.data.total;
    },
    //监听pagesize改变
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize;
      this.getCate();
    }, //监听页码的变化
    handleCurrentChange(page) {
      this.queryInfo.pagenum = page;
      this.getCate();
    },
    addCate() {
      this.getParentCate();
      this.showAddDialog = true;
    },
    async getParentCate() {
      const { data: res } = await this.$request({
        url: "categories",
        params: {
          type: 2,
        },
      });

      if (res.meta.status !== 200) {
        return;
      }
      //console.log(res.data);
      this.parentCateList = res.data;
    },
    handleAddChange() {
      //如果selectoption的length=0说明没有选父级分类
      if (this.selectoption.length > 0) {
        //数组的最后一项id为父级id
        this.addCateForm.cat_pid = this.selectoption[
          this.selectoption.length - 1
        ];
        this.addCateForm.cat_level = this.selectoption.length;
      } else {
        //父级id
        this.addCateForm.cat_pid = 0;
        //为当前分类等级赋值
        this.addCateForm.cat_level = 0;
      }
      //console.log(this.selectoption);
    },

    commitAdd() {
      this.$refs.addCateRef.validate(async (val) => {
        if (val) {
          const { data: res } = await this.$request({
            url: "categories",
            method: "post",
            data: this.addCateForm,
          });
          console.log(res);
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg);
          }
          this.$message.success(res.meta.msg);
          this.getCate();
          this.showAddDialog = false;
        }
      });
      console.log(this.addCateForm);
    },
    //关闭添加分类的对话框
    closeAddDiglog() {
      this.$refs.addCateRef.resetFields();
      this.selectoption = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    //根据id查询每行的数据
    async getRowCate(id) {
      this.getParentCate();
      const { data: res } = await this.$request({
        url: `categories/${id}`,
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.rowCateForm = res.data;
      this.showEditDialog = true;
    },
    closeEdit() {
      this.$refs.editCateRef.resetFields();
      /* this.editselectoption = [];
      this.rowCateForm.cat_pid = 0;
      this.rowCateForm.cat_level = 0; */
    },
    //确认编辑
    commitEdit() {
      this.$refs.editCateRef.validate(async (val) => {
        if (val) {
          const { data: res } = await this.$request({
            url: "categories/" + this.rowCateForm.cat_id,
            method: "put",
            data: {
              cat_name: this.rowCateForm.cat_name,
            },
          });
          console.log(res);
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg);
          }
          this.getCate();
          this.$message.success(res.meta.msg);
          this.showEditDialog = false;
        }
      });
    },
    //删除操作
    async showDeleteCate(id) {
      const res = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => {
        return err;
      });
      console.log(res);
      if (res !== "confirm") {
        return this.$message({
          type: "info",
          message: "已取消删除",
        });
      }

      const { data: ress } = await this.$request({
        url: "categories/" + id,
        method: "delete",
      });
      console.log(ress);
      if (ress.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.getCate();
      this.$message.success(ress.meta.msg);
    },
  },
  created() {
    this.getCate();
  },
};
</script>
<style scoped>
.el-card {
  margin-top: 30px;
}
.el-cascader {
  width: 100%;
}
</style>
